<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Sales\Service;


use Admin\Entity\SelfLocation;
use Doctrine\ORM\EntityManager;
use Sales\Entity\OrderSelfLocation;
use Shop\Common\ShopCommon;

class OrderSelfLocationManager
{
    private $entityManager;

    public function __construct(
        EntityManager $entityManager
    )
    {
        $this->entityManager = $entityManager;
    }

    /**
     * 添加订单自提点
     * @param $locationId
     * @param $orderId
     * @return OrderSelfLocation
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addOrderSelfLocation($locationId, $orderId)
    {
        $locationInfo = $this->entityManager->getRepository(SelfLocation::class)->findOneBy(['locationId' => $locationId]);

        $orderLocation= new OrderSelfLocation();
        $orderLocation->valuesSet($locationInfo->valuesArray());
        $orderLocation->setOrderId($orderId);

        $this->entityManager->persist($orderLocation);
        $this->entityManager->flush();

        return $orderLocation;
    }

    /**
     * 编辑订单自提点
     * @param array $data
     * @param OrderSelfLocation $orderSelfLocation
     * @return OrderSelfLocation
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editOrderSelfLocation(array $data, OrderSelfLocation $orderSelfLocation)
    {
        $orderSelfLocation->valuesSet($data);
        $this->entityManager->flush();

        return $orderSelfLocation;
    }

    /**
     * 添加提货码
     * @param $orderId
     * @return bool
     */
    public function addOrderSelfLocationTakeCode($orderId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->update(OrderSelfLocation::class, 'l')
            ->set('l.takeCode', ':takeCode')->setParameter('takeCode', ShopCommon::createTackCode())
            ->where('l.orderId = :orderId')->setParameter('orderId', $orderId);
        $qb->getQuery()->execute();

        return true;
    }

    /**
     * 删除订单自提点
     * @param $orderId
     * @return bool
     */
    public function deleteOrderSelfLocation($orderId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->delete(OrderSelfLocation::class, 'l')->where('l.orderId = :orderId')->setParameter('orderId', $orderId);
        $qb->getQuery()->execute();

        return true;
    }
}